<template>
    <div class="template-config-edit">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>{{ isEdit ? '编辑模板配置' : '新增模板配置' }}</span>
                    <el-button @click="goBack">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        返回列表
                    </el-button>
                </div>
            </template>

            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="template-form">
                <!-- 模板编号 -->
                <el-form-item label="模板编号" prop="templateNumber">
                    <el-input v-model="form.templateNumber" placeholder="请输入模板编号" clearable :disabled="isEdit" />
                    <div v-if="isEdit" class="form-tip">编辑时模板编号不可修改</div>
                </el-form-item>

                <!-- Logo上传 -->
                <el-form-item label="Logo" prop="logo">
                    <el-upload ref="logoUploadRef" class="logo-uploader" :action="uploadUrl" :show-file-list="false"
                        :on-success="handleLogoSuccess" :before-upload="beforeLogoUpload" :headers="uploadHeaders">
                        <img v-if="form.logo" :src="form.logo" class="logo-preview" />
                        <el-icon v-else class="logo-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <div class="upload-tip">只能上传jpg/png文件，且不超过2MB</div>
                </el-form-item>

                <!-- 首页背景图 -->
                <el-form-item label="首页背景图" prop="backgroundImage">
                    <el-upload ref="bgUploadRef" class="bg-uploader" :action="uploadUrl" :show-file-list="false"
                        :on-success="handleBgSuccess" :before-upload="beforeBgUpload" :headers="uploadHeaders">
                        <img v-if="form.backgroundImage" :src="form.backgroundImage" class="bg-preview" />
                        <el-icon v-else class="bg-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <div class="upload-tip">只能上传jpg/png文件，且不超过5MB</div>
                </el-form-item>

                <!-- 开屏页动画 -->
                <el-form-item label="开屏页动画" prop="splashMedia">
                    <el-upload ref="splashUploadRef" class="splash-uploader" :action="uploadUrl" :show-file-list="false"
                        :on-success="handleSplashSuccess" :before-upload="beforeSplashUpload" :headers="uploadHeaders">
                        <div v-if="form.splashMedia" class="splash-preview">
                            <video v-if="isVideo(form.splashMedia)" :src="form.splashMedia" controls
                                class="media-preview" />
                            <img v-else :src="form.splashMedia" class="media-preview" />
                        </div>
                        <el-icon v-else class="splash-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <div class="upload-tip">支持上传图片(jpg/png)或视频(mp4)文件，不超过10MB</div>
                </el-form-item>

                <!-- 操作按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="loading">
                        {{ isEdit ? '更新配置' : '保存配置' }}
                    </el-button>
                    <el-button @click="resetForm">重置</el-button>
                    <el-button @click="goBack">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import {
    saveWebsiteConfig,
    getWebsiteConfig,
    type TemplateConfigData
} from '@/api/template_config'

const route = useRoute()
const router = useRouter()

// 表单引用
const formRef = ref<FormInstance>()
const logoUploadRef = ref()
const bgUploadRef = ref()
const splashUploadRef = ref()

// 加载状态
const loading = ref(false)
const pageLoading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)
const configId = computed(() => Number(route.params.id))

// 上传配置
const uploadUrl = import.meta.env.VITE_APP_BASE_URL + 'api/upload'
const uploadHeaders = {
    Authorization: 'Bearer ' + localStorage.getItem('token')
}

// 表单数据
const form = reactive({
    id: undefined as number | undefined,
    templateNumber: '',
    logo: '',
    backgroundImage: '',
    splashMedia: ''
})

// 表单验证规则
const rules: FormRules = {
    templateNumber: [
        { required: true, message: '请输入模板编号', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    logo: [
        { required: true, message: '请上传Logo', trigger: 'change' }
    ],
    backgroundImage: [
        { required: true, message: '请上传首页背景图', trigger: 'change' }
    ],
    splashMedia: [
        { required: true, message: '请上传开屏页动画', trigger: 'change' }
    ]
}

// 判断是否为视频文件
const isVideo = (url: string): boolean => {
    return url.toLowerCase().includes('.mp4') || url.toLowerCase().includes('video')
}

// Logo上传前验证
const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isJPGOrPNG) {
        ElMessage.error('Logo只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('Logo大小不能超过 2MB!')
        return false
    }
    return true
}

// Logo上传成功回调
const handleLogoSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.logo = response.data.url
        ElMessage.success('Logo上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 背景图上传前验证
const beforeBgUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt5M = rawFile.size / 1024 / 1024 < 5

    if (!isJPGOrPNG) {
        ElMessage.error('背景图只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('背景图大小不能超过 5MB!')
        return false
    }
    return true
}

// 背景图上传成功回调
const handleBgSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.backgroundImage = response.data.url
        ElMessage.success('背景图上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 开屏页动画上传前验证
const beforeSplashUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isVideo = rawFile.type === 'video/mp4'
    const isLt10M = rawFile.size / 1024 / 1024 < 10

    if (!isImage && !isVideo) {
        ElMessage.error('开屏页动画只能是 JPG/PNG/MP4 格式!')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB!')
        return false
    }
    return true
}

// 开屏页动画上传成功回调
const handleSplashSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        form.splashMedia = response.data.url
        ElMessage.success('开屏页动画上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 加载配置详情
const loadConfigDetail = async () => {
    if (!isEdit.value) return

    pageLoading.value = true
    try {
        const response = await getWebsiteConfig(configId.value)
        if (response.code === 1) {
            const config = response.data
            form.id = config.id
            form.templateNumber = config.templateNumber || ''
            form.logo = config.logo || ''
            form.backgroundImage = config.backgroundImage || ''
            form.splashMedia = config.splashMedia || ''
        } else {
            ElMessage.error(response.msg || '获取配置详情失败')
            goBack()
        }
    } catch (error) {
        console.error('加载配置详情失败:', error)
        ElMessage.error('获取配置详情失败')
        goBack()
    } finally {
        pageLoading.value = false
    }
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true

        let response
        
        // 新增配置
        response = await saveWebsiteConfig(form as TemplateConfigData)

        if (response.code === 1) {
            ElMessage.success(isEdit.value ? '更新成功' : '保存成功')
            goBack()
        } else {
            ElMessage.error(response.msg || (isEdit.value ? '更新失败' : '保存失败'))
        }

        loading.value = false
    } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(isEdit.value ? '更新失败，请重试' : '保存失败，请重试')
        loading.value = false
    }
}

// 重置表单
const resetForm = () => {
    ElMessageBox.confirm('确定要重置表单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        if (isEdit.value) {
            // 编辑模式下重新加载数据
            loadConfigDetail()
        } else {
            // 新增模式下清空表单
            formRef.value?.resetFields()
            form.templateNumber = ''
            form.logo = ''
            form.backgroundImage = ''
            form.splashMedia = ''
        }
        ElMessage.success('表单已重置')
    })
}

// 返回列表
const goBack = () => {
    router.push('/template-config/list')
}

// 组件挂载时加载数据
onMounted(() => {
    if (isEdit.value) {
        loadConfigDetail()
    }
})
</script>

<style scoped>
.template-config-edit {
    padding: 20px;
}

.box-card {
    max-width: 800px;
    margin: 0 auto;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
}

.template-form {
    margin-top: 20px;
}

.form-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
}

/* Logo上传样式 */
.logo-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.logo-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.logo-preview {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* 背景图上传样式 */
.bg-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 200px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.bg-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.bg-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.bg-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 开屏页动画上传样式 */
.splash-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 200px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.splash-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.splash-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.splash-preview {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.media-preview {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
}
</style>